<template>
	<view class="home">
		<view class="top">
			<view class="type-title" @click="open">
				<!-- 类型名称 -->
				<text class="title">{{query.cateName}}</text>
				<uni-icons color="#fff" type="bars" size="25"></uni-icons>
			</view>
			<view class="content">
				<view class="time" @click="openTime">
					<text>{{query.timeName}}</text>
					<uni-icons color="#fff" type="fire" size="20"></uni-icons>
				</view>
				<view class="">
					<uni-tag :text="'总支出:￥'+totalOut" type="error" />
					<!-- <van-tag type="danger" >总支出:￥{{totalOut}}</van-tag> -->
					<text></text>
				</view>
				<view class="">
					<uni-tag :text="'总收入:￥'+totalIn" type="primary" />
					<!-- <text>总收入:￥{{totalIn}}</text> -->
				</view>
			</view>
		</view>


		<!-- 显示数据 -->
		<scroll-view scroll-y class="list">
			<uni-card :title="item.month" margin='10px' v-for="item in infoList" :key="item.month">
				<view class="item" v-for="child in item.data" :key="child.id" @click="toDetail(child)">
					<view class="left">
						<uni-icons type="contact" color="#38A678" size="30"></uni-icons>
						<view class="title">
							<text class="panel">{{child.cate | toCate}}</text>
							<text class="detail">{{child.detail}}</text>
						</view>
					</view>
					<view class="right">
						<!-- {{child.type==0?'-':'+'}} {{child.money}} -->
						<uni-tag :inverted="true" v-if="child.type==0" :text="'-'+child.money" type="error" />
						<uni-tag :inverted="true" v-else :text="'+'+child.money" type="success" />
					</view>
				</view>
			</uni-card>
			<view class="bottom">
				滑到底了!
			</view>
		</scroll-view>



		<!-- 点击全部类型的弹出框 -->
		<uni-popup ref="popup" background-color="#fff" type="bottom" class="type-content">
			<view class="item first">选择类型</view>
			<view class="item" v-for="item in cateList2" :key="item.id" @click="typeChange(item)">
				{{item.name}}
			</view>
		</uni-popup>

		<!-- 时间 -->
		<uni-popup ref="popupTime" background-color="#fff" type="bottom" class="type-content">
			<van-datetime-picker type="year-month" :max-date="maxDate" :value="currentDate" :min-date="minDate"
				@confirm="onSubmit()" @cancel="cancel" />
		</uni-popup>

		<view class="add" @click="toAdd">
			<van-icon name="records" color="#38A678" />记一笔
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				currentDate: new Date().getTime(), // 选中时间
				maxDate: new Date().getTime(), // 最大时间--今天
				minDate: new Date(2020, 0, 1), // 最小时间
				cateList2: [{ // 类型
						id: 0,
						name: '全部类型'
					},
					// {
					// 	id: 1,
					// 	name: "餐饮"
					// },
					// {
					// 	id: 2,
					// 	name: "交通"
					// }, {
					// 	id: 3,
					// 	name: "购物"
					// }, {
					// 	id: 4,
					// 	name: "娱乐"
					// }, {
					// 	id: 5,
					// 	name: "生活缴费"
					// }, {
					// 	id: 6,
					// 	name: "红包转账"
					// },
				],
				infoList: [], // 记账 数据
				// 查询条件
				query: {
					cateId: 0,
					cateName: '全部类型',
					timeName: new Date(),
					phone: "123456789"
				},
				totalOut: 0, //总支出
				totalIn: 0, //总收入
			};
		},
		filters: {
			toCate(val) { // 过滤渲染数据的分类
				let st = ''
				switch (val) {
					case 1:
						st = '餐饮';
						break;
					case 2:
						st = '交通';
						break;
					case 3:
						st = '购物';
						break;
					case 4:
						st = '娱乐';
						break;
					case 5:
						st = '生活缴费';
						break;
					case 6:
						st = '红包转账';
						break;
				}
				return st;
			}
		},
		computed: {
			...mapState('m_user', ['userInfo']),
			...mapState('m_cate', ['cateList']),
		},
		onLoad() {
			this.query.phone = this.userInfo.username
			this.query.timeName = this.formatDate(this.query.timeName, 'yyyy-MM')
			this.getList()
			this.cateList2 = [...this.cateList2, ...this.cateList]
		},
		methods: {
			// 根据时间\类型,查询当月支出-收入数据
			async getList() {
				console.log("打印查询参数:", this.query);
				const {
					data: res
				} = await uni.$http.post("/info/findAll", {
					cate: this.query.cateId,
					month: this.query.timeName,
					phone: this.query.phone
				})
				console.log("记账list:", res);
				if (res.code == 0) {
					console.log("查询成功");
				}
				this.infoList = this.Classification(res.data, 'month')
				this.totalOut = 0
				this.totalIn = 0
				res.data.forEach((item) => {
					if (item.type == 0) {
						this.totalOut += item.money
					} else {
						this.totalIn += item.money
					}
				})

			},
			// 打开类型
			open() {
				uni.showLoading({
					title: '加载中'
				});
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('bottom')
				uni.hideLoading()
			},
			// 确定类型
			typeChange(item) {
				console.log('点击了', item.id, item.name);
				// 对查询分类进行赋值
				this.query.cateName = item.name
				this.query.cateId = item.id
				this.$refs.popup.close()
				// 重新执行查询操作
				this.getList()
			},
			// 打开时间选择
			openTime() {
				this.$refs.popupTime.open('bottom')
			},
			// 时间框点击确认
			onSubmit(event) {
				// console.log(event.detail);
				let date = new Date(event.detail)
				this.query.timeName = this.formatDate(date, 'yyyy-MM')
				// console.log(date, this.formatDate(date, 'yyyy-MM'));
				this.$refs.popupTime.close()
				// 重新执行查询操作
				this.getList()
			},
			// 时间框返回
			cancel() {
				this.$refs.popupTime.close()
			},
			// 点击了记一笔
			toAdd() {
				uni.navigateTo({
					url: '../add/add'
				});
			},
			// 点击了记账列表中的一条信息
			toDetail(child) {
				console.log("点击了记账列表", child);
				uni.navigateTo({
					url: '../../subpkg/home-detail/home-detail?query=' + JSON.stringify(child)
				});
			},
			// 时间戳转换成   年月日时分秒  2022-06-01 00:00
			// date为  Fri Apr 01 2022 00:00:00 GMT+0800 (中国标准时间)
			// 执行方法为  formatDate(date, 'yyyy-MM-dd hh:mm')
			formatDate(date, fmt) {
				if (/(y+)/.test(fmt)) {
					fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
				}
				let o = {

					'M+': date.getMonth() + 1,
					'd+': date.getDate(),
					'h+': date.getHours(),
					'm+': date.getMinutes(),
					's+': date.getSeconds()
				}
				for (let k in o) {
					if (new RegExp(`(${k})`).test(fmt)) {
						let str = o[k] + ''
						fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : this.padLeftZero(str))
					}
				}
				return fmt
			},
			padLeftZero(str) {
				return ('00' + str).substr(str.length)
			},


			// 把数组按照属性重新分类
			Classification(list, key) {
				const res = [];
				list.map((item) => {
					const index = this.FindIndex(res, key, item[key]);
					if (index >= 0) {
						res[index].data.push(item);
					} else {
						const obj = {};
						obj[key] = item[key];
						obj.data = [item];
						res.push(obj);
					}
				});
				return res;
			},
			// 方法配套使用
			FindIndex(array, key, com) {
				let index = -1;
				array.map((item, _index) => {
					if (item[key] === com) {
						index = _index;
					}
				});
				return index;
			},
		},
		// 钩子函数
		onPullDownRefresh() {
			this.getList()
			setTimeout(() => {
				//关闭下拉刷新
				uni.stopPullDownRefresh()
			}, 3000)
		}
	}
</script>

<style lang="scss">
	.top {
		height: 120px;
		background-color: #38A678;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		padding: 10px;
		box-sizing: border-box;
		color: #fff;

		.type-title {
			background-color: #3399cc;
			display: flex;
			align-items: center;
			justify-content: center;
			height: 30px;
			width: 100px;

		}

		.content {
			display: flex;

			align-items: center;

			view {
				margin: 0 5px;
				display: flex;
				text-align: center;
			}

			font-size: 16px;
		}
	}

	// 每一项
	.list {
		height: calc(100vh - 120px);
		box-sizing: border-box;

		.item {
			display: flex;
			justify-content: space-between;
			border-bottom: 1px solid #ccc;
			// padding: 5px 0;
			height: 60px;

			.left {
				display: flex;
				align-items: center;

				.title {
					display: flex;
					flex-direction: column;
					margin-left: 10px;

					.panel {
						font-size: 20px;
						font-weight: bold;
					}

					.detail {
						color: #999;
					}
				}
			}

			.right {
				height: 100%;
				font-size: 25px;
				line-height: 60px;
			}
		}

		// 滑到底了!
		.bottom {
			text-align: center;
			background-color: #eee;
			height: 40px;
			line-height: 40px;
		}
	}


	// 全部类型的选择框
	.type-content {
		display: flex;
		flex-direction: column;

		.item {
			height: 50px;
			display: flex;
			align-items: center;
			justify-content: center;
			border-bottom: 1px solid #999;
		}

		.first {
			color: #999;
		}
	}

	.add {
		position: absolute;
		bottom: 20px;
		right: 20px;
		padding: 10px;
		color: #38A678;
		box-shadow: 0 0 5px 1px #666;
		background-color: #fff;
		border-radius: 20px;
	}
</style>
